Authentication and Authorization
December 10, 2019
If We Are Having Some Protected Routes That Provides Resources and Informational Data To User Without Authentication And Authorization Then There Will Be Compromise With The Sensitive Information That’s Why We Implemented The Auth Part To Protect Our Application
Using The Jwt Tokens To Making The Protected Routes:-
Jwt Is Called JsonWebToken Which Generates The Json Token.When The Client Side Information Comes To Server The Mongodb Database Verifies The Information Then The Jwt Comes In Play To Generate The Token.
Example:-
var token = auth.generateToken({userid: user._id})
Here We Are Generating The Token By Using The Jwt It Takes a Parameter Which Can Be Used for Generating The Token.That Parameter Is Either The User _id Provided By The Mongodb Or The Username
Now Using The Jwt Token For Making Our Route Protected:-
To Making The Route Protected We Just Have To Implemented That Token based Authentication In Our Route So When Someone Passes Through Our Route He Just Have To Passed Through The Middleware Which Verifies That The Particular User Is having Token Or Not If It Is Having The Token Then He Will Be Able To Access The Particular Route Otherwise Not. Example:-
//protectedRoute
router.get("/users", auth.verifyToken, (req, res) => {
UserModel.find({}, (err, users) => {
if (err) res.json({ Error: ErrorFounded })
res.json({ users: users })
})
})By This Way We Can Protect Our Any Route By using The jwt Authentication.
Middleware Which Can Generates The Token And Verifies The Token:-
//requring the token
var jwt = require("jsonwebtoken")//generating the middleware for token generating
module.exports.generateToken = function(payload) {
return jwt.sign(payload, "abcdef")
}//generating the verify middleware
module.exports.verifyToken = function(req, res, next) {
var token = req.headers.authorization || ""
if (token) {
jwt.verify(token, "abcdef", (err, decoded) => {
// console.log(decoded)
if (err) res.json({ token: "notVerify" })
next()
})
} else {
return res.json({ token: "notFound" })
}
}Any Request Comes To A Particular Route It Must Have To Be Passes Through It That’s How Whole Authentication AndAuthorization Works.